from PySide6.QtCore import Slot, Qt
from PySide6.QtWidgets import QWidget, QHBoxLayout, QVBoxLayout
from qfluentwidgets import (
    BodyLabel,
    LineEdit,
    ComboBox,
    PushButton,
    FluentIcon,
    FlyoutViewBase,
    PrimaryPushButton,
    InfoBar,
    InfoBarPosition,
)

from app.utils.BaseMsg import MsgLatOrLon

global content, title, show_time


class ErrorMsg(FlyoutViewBase):

    def __init__(self, lat, lon, parent=None):
        super().__init__(parent)
        self.v_box_layout = QVBoxLayout(self)
        self.label = BodyLabel(text=f"输入信息经纬度{lat, lon}格式错误！！！")
        self.button = PrimaryPushButton(text="关闭")

        self.button.setFixedWidth(120)
        self.v_box_layout.setSpacing(24)
        self.v_box_layout.setContentsMargins(20, 16, 20, 16)
        self.v_box_layout.addWidget(self.label)
        self.v_box_layout.addWidget(self.button)


class LatLonToFloat2(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setObjectName("经纬度转换")

        # 经纬度转换浮点数
        self.label_lon = BodyLabel()
        self.label_lon.setText("经度：")
        self.check_lon = ComboBox()
        self.check_lon.addItems(["东经", "西经"])
        self.input_lon = LineEdit()
        self.input_lon.setPlaceholderText("DDD MM SSS")

        self.label_lat = BodyLabel()
        self.label_lat.setText("纬度：")
        self.check_lat = ComboBox()
        self.check_lat.addItems(["南纬", "北纬"])
        self.input_lat = LineEdit()
        self.input_lat.setPlaceholderText("DD MM SSS")

        self.button_conv = PushButton(FluentIcon.SYNC, "转换")
        self.button_clear = PushButton(FluentIcon.CLEAR_SELECTION, "清空")

        layout_lon = QHBoxLayout()
        layout_lon.addWidget(self.label_lon)
        layout_lon.addWidget(self.check_lon)
        layout_lon.addWidget(self.input_lon)

        layout_lat = QHBoxLayout()
        layout_lat.addWidget(self.label_lat)
        layout_lat.addWidget(self.check_lat)
        layout_lat.addWidget(self.input_lat)

        layout_button = QHBoxLayout()
        layout_button.addWidget(self.button_conv)
        layout_button.addWidget(self.button_clear)

        layout = QVBoxLayout()
        layout.addLayout(layout_lon)
        layout.addLayout(layout_lat)
        layout.addLayout(layout_button)

        # 浮点数转经纬度

        self.label_lon2 = BodyLabel()
        self.label_lon2.setText("经度：")
        # self.label_lon.setTextColor(QColor(0, 255, 0), QColor(255, 0, 0))

        self.input_lon2 = LineEdit()
        self.input_lon2.setPlaceholderText("120.5555")
        self.input_lon2.setClearButtonEnabled(True)

        self.label_lat2 = BodyLabel()
        self.label_lat2.setText("纬度：")
        # self.label_lat.setTextColor(QColor(0, 255, 0), QColor(255, 0, 0))

        self.input_lat2 = LineEdit()
        self.input_lat2.setPlaceholderText("55.5555")
        self.input_lat2.setClearButtonEnabled(True)

        self.button_conv2 = PushButton(FluentIcon.SYNC, "转换")
        self.button_clear2 = PushButton(FluentIcon.CLEAR_SELECTION, "清空")

        lon_layout2 = QHBoxLayout()
        lon_layout2.addWidget(self.label_lon2)
        lon_layout2.addWidget(self.input_lon2)

        lat_layout2 = QHBoxLayout()
        lat_layout2.addWidget(self.label_lat2)
        lat_layout2.addWidget(self.input_lat2)

        button_layout2 = QHBoxLayout()
        button_layout2.addWidget(self.button_conv2)
        button_layout2.addWidget(self.button_clear2)

        layout2 = QVBoxLayout()
        layout2.addLayout(lon_layout2)
        layout2.addLayout(lat_layout2)
        layout2.addLayout(button_layout2)

        main_layout = QVBoxLayout()
        main_layout.addLayout(layout)
        main_layout.addLayout(layout2)

        self.setLayout(main_layout)

        self.button_conv.clicked.connect(self.convert)
        self.button_clear.clicked.connect(self.clear)

        self.button_conv2.clicked.connect(self.convert2)
        self.button_clear2.clicked.connect(self.clear2)

    @Slot()
    def convert(self):
        """

        :return:
        """

        def str_format(s):
            try:
                return int(s)
            except ValueError:
                return s

        def is_valid_coordinate(coord_str: str, is_lon: bool = False):
            parts = coord_str.strip().split()
            print(parts)
            if len(parts) != 4:
                if is_lon:
                    return False, ("Error", "经度格式输入错误")
                else:
                    return False, ("Error", "纬度格式输入错误")

            try:
                degrees, minutes, seconds, direction = list(map(str_format, parts))
                print("1", degrees, minutes, seconds, direction)
                print("2", type(degrees), type(minutes), type(seconds), type(direction))
                if is_lon:
                    if (
                        degrees > 180
                        or minutes > 60
                        or seconds > 60
                        or (minutes == 60 and seconds > 0)
                        or (degrees == 180 and (minutes > 0 or seconds > 0))
                    ):
                        return False, ("Error", "经度格式输入错误")
                else:
                    if (
                        degrees > 90
                        or minutes > 60
                        or seconds > 60
                        or (minutes == 60 and seconds > 0)
                        or (degrees == 90 and (minutes > 0 or seconds > 0))
                    ):
                        return False, ("Error", "纬度格式输入错误")
                dd = degrees + minutes / 60 + seconds / 3600
                print(dd)
                if direction in ["S", "W"]:
                    dd *= -1

                return True, ("Success", str(dd))

            except ValueError:
                return False, ("Error", "数据格式错误，请输入数字")

        global content, title, show_time
        show_time = 1000
        lon_direction = self.check_lon.currentText()
        lat_direction = self.check_lat.currentText()
        lat_value = self.input_lat.text().strip()
        lon_value = self.input_lon.text().strip()
        print(lon_value, lat_value)
        if lon_value and lat_value:
            lon = lon_value + " E" if lon_direction == "东经" else lon_value + " W"
            lat = lat_value + " N" if lat_direction == "北纬" else lat_value + " S"
            # if len(lon.split()) != 4 or len(lat.split()) != 4:
            #     title = "Error"
            #     content = "输入信息经度{}，纬度：{} 格式错误".format(lon, lat)
            longitude_dd = is_valid_coordinate(lon, True)
            latitude_dd = is_valid_coordinate(lat)
            print(longitude_dd, latitude_dd)
            if not longitude_dd[0] or not latitude_dd[0]:  # 经纬度任意一个转换失败
                title = "Error"
                __content = ""
                if not longitude_dd[0]:
                    __content += longitude_dd[1][1]
                if not latitude_dd[0]:
                    __content += latitude_dd[1][1]
                content = __content
            else:
                title = "Success"
                content = longitude_dd[1][1] + latitude_dd[1][1]
                show_time = -1

        elif not lon_value:
            title = "Error"
            content = "经度为空"
        elif not lat_value:
            title = "Error"
            content = "纬度为空"
        elif not lon_value and not lat_value:
            title = "Error"
            content = "经度和纬度都为空"
        if title == "Error":
            InfoBar.warning(
                title=title,
                content=content,
                orient=Qt.Orientation.Horizontal,
                position=InfoBarPosition.BOTTOM,
                duration=show_time,  # 永不消失
                parent=self,
            )
        else:
            InfoBar.info(
                title=title,
                content=content,
                orient=Qt.Orientation.Horizontal,
                position=InfoBarPosition.BOTTOM,
                duration=show_time,
                parent=self,
            )

    @Slot()
    def convert2(self):
        """

        :return:
        """
        tt = MsgLatOrLon(
            self.input_lon2.text(),
            self.input_lat2.text(),
            self.input_lon2.text(),
            self.input_lat2.text(),
            self,
        )
        if tt.exec():
            print(tt.old_label_lon.text(), tt.old_label_lat.text())

    @Slot()
    def clear(self):
        """

        :return:
        """
        self.input_lat.clear()
        self.input_lon.clear()

    @Slot()
    def clear2(self):
        """

        :return:
        """
        self.input_lat2.clear()
        self.input_lon2.clear()
